package com.party.core.service.crowdfund.impl;

import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.*;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.crowdfund.biz.CrowdfundReviseBizService;
import com.party.core.service.order.IOrderFormService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 众筹校正数据
 * Created by wei.li
 *
 * @date 2017/7/3 0003
 * @time 18:47
 */

@Service
public class ProjectReviseService implements IProjectReviseService {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ISupportService supportService;
    @Autowired
    private IOrderFormService orderFormService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Autowired
    private IProjectGradationService projectGradationService;
    @Autowired
    private IEventGradationService eventGradationService;
    @Autowired
    private IProjectInfoGradationService projectInfoGradationService;
    @Autowired
    private CrowdfundReviseBizService crowdfundReviseBizService;

    /**
     * 校正数据
     *
     * @param id 编号
     */
    @Override
    public Project reviseFavorer(String id) {
        Project project = projectService.get(id);
        crowdfundReviseBizService.reviseProjectData(project);
        return project;
    }

    @Override
    public void reviseMultiProject(Project project) {
        try {
            String id = project.getId();
            CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(id);
            if (null != crowdfundEvent && YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                List<EventGradation> eventGradations = eventGradationService.findByEventId(crowdfundEvent.getId());
                boolean updateInfo = false;
                for (int i = 0; i < eventGradations.size(); i++) {
                    EventGradation eventGradation = eventGradations.get(i);
                    Double effectiveAmount = 0d;
                    Date projectLastEndTime = null;
                    Date lastEndTime = null;
                    ProjectGradation projectGradation = projectGradationService.
                            getUnique(new ProjectGradation(id, eventGradation.getId()));
                    if (null != projectGradation && !YesNoStatus.NO.getCode().equals(projectGradation.getCompetitionStatus())) {
                        if (i > 0) {
                            project = projectService.get(id);
                            effectiveAmount = projectGradationService.getEffectiveAmount(eventGradation.getEndTime(), id);
                        }

                        Double subAmount = BigDecimalUtils.sub(project.getRealTimeAmount(), effectiveAmount);
                        subAmount = BigDecimalUtils.round(subAmount, 2);

                        String successTimeStr = DateUtils.formatDate(projectGradation.getSuccessTime(), DateUtils.DATE_PATTERN);

                        /**
                         * 1、剩余金额小于当前阶段的目标金额，同时当前阶段未截止，就把当前阶段设为正在筹的阶段
                         * 2、当前阶段为最后一个阶段，就把当前阶段设为正在筹的阶段
                         * 3、剩余金额等于当前阶段的目标
                         *
                         **/
                        if (subAmount >= projectGradation.getTargetAmount()) {
                            if (ProjectGradation.DEFAULT_SUCCESS_TIME.equals(successTimeStr)) {
                                // 当前阶段没有结束，成功时间设为当前时间
                                // 如果当前众筹阶段为第一个报名阶段，useTime则用当前时间和报名时间比较
                                // 如果当前众筹阶段不是第一个报名阶段，useTime则用上个阶段的截止时间比较

                                String currentDateStr = DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
                                String endTimeStr = DateUtils.formatDate(eventGradation.getEndTime(), DateUtils.DATE_PATTERN);

                                if (currentDateStr.equals(endTimeStr) || eventGradation.getEndTime().before(new Date())) {
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.setTime(eventGradation.getEndTime());
                                    calendar.set(Calendar.HOUR, -5);
                                    projectGradation.setSuccessTime(calendar.getTime());
                                } else {
                                    projectGradation.setSuccessTime(new Date());
                                }

                                if (i == 0 || null == projectLastEndTime) {
                                    projectGradation.setUseTime(System.currentTimeMillis() - project.getCreateDate().getTime());
                                } else {
                                    projectGradation.setUseTime(System.currentTimeMillis() - lastEndTime.getTime());
                                }
                                projectGradationService.update(projectGradation);
                            }
                        }
                        if ((i == eventGradations.size() - 1 && subAmount.equals(projectGradation.getTargetAmount()))
                                || (subAmount < projectGradation.getTargetAmount() && eventGradation.getEndTime().after(new Date()))
                                || i == eventGradations.size() - 1) {
                            if (!updateInfo) {
                                updateInfo = true;

                                ProjectInfoGradation infoGradation = projectInfoGradationService.findByProjectId(projectGradation.getProjectId());
                                infoGradation.setProjectGradationId(projectGradation.getId());
                                projectInfoGradationService.update(infoGradation);
                            }
                        }
                        if (subAmount < projectGradation.getTargetAmount() && eventGradation.getEndTime().after(new Date())
                                || (i == eventGradations.size() - 1 && subAmount < projectGradation.getTargetAmount())) {
                            if (!ProjectGradation.DEFAULT_SUCCESS_TIME.equals(successTimeStr)) {
                                projectGradation.setCompetitionStatus(3); // 设为空
                                projectGradation.setUseTime(0L);
                                projectGradation.setSuccessTime(DateUtils.parse(ProjectGradation.DEFAULT_SUCCESS_TIME, DateUtils.DATE_PATTERN));
                                projectGradationService.update(projectGradation);
                            }
                        }
                        projectLastEndTime = eventGradation.getEndTime();
                    }
                    lastEndTime = eventGradation.getEndTime();
                }
            }
        } catch (Exception e) {
            logger.error("校正异常", e);
        }
    }

    /**
     * 校正众筹目标
     *
     * @param activityId 众筹目标
     */
    @Override
    public void reviseTarget(String activityId) {
        Activity activity = activityService.get(activityId);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
        activity.setIsMultiple(crowdfundEvent.getIsMultiple());
        crowdfundReviseBizService.reviseTargetData(activity);
    }
}
